/* eslint-disable react/prop-types */
import React from 'react';
import { TeamixAvatar, Input, Button, Message } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
// import ListEmpty from 'atComponents/ListEmpty';
import ConversationTimeLine from './conversation';
import KEYCODE from 'utils/keycode';
import { ENUM } from 'utils/constants';
import intl from '../../../locale';

import '../index.scss';

const { ctrlKey, ctrlTxt } = ENUM.getOSKeyMap();
const { ImageAvatar, TextAvatar } = TeamixAvatar;

class commitComment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowMore: false, // 是否展示更多评论
      value: '',
    };
  }

  renderCommentList = () => {
    const conversations = this.getConversations();
    return (
      conversations.length > 0 && (
        <div className="commit-comment-right-list">
          {conversations.map((item) => {
            return <ConversationTimeLine data={item} key={item.id} {...this.props} />;
          })}
        </div>
      )
    );
  };

  getConversations = () => {
    const { commentList } = this.props;
    const { isShowMore } = this.state;
    // 递归形成讨论块：以无parent_id的评论作为讨论块的跟节点，其子评论平铺在下面
    const conversations = [];
    /* eslint no-unused-expressions: ["error", { "allowTernary": true }] */
    // eslint-disable-next-line no-unused-expressions
    commentList &&
      commentList.forEach((comment) => {
        const isRoot = !comment.parent_id;
        if (isRoot) {
          conversations.push([comment]);
        } else {
          conversations.forEach((conversation) => {
            conversation.forEach((childItem) => {
              if (childItem.id === comment.parent_id) {
                conversation.push(comment);
              }
            });
          });
        }
      });
    let curConversations = [];
    const conversationsLength = conversations.length;
    if (conversationsLength > 8) {
      if (isShowMore) {
        curConversations = conversations.slice(conversationsLength - 8, conversationsLength);
      } else {
        curConversations = conversations;
      }
    } else {
      curConversations = conversations;
    }
    return curConversations;
  };

  getConversationsLength = (commentList) => {
    if (commentList) {
      return commentList.filter((item) => !item.parent_id).length;
    }
    return 0;
  };

  // 提交整体评论或者草稿
  onSubmitWhole = (value) => {
    if (!value || value.trim().length <= 0) {
      Message.error({
        title: '评论内容不能为空',
      });
      return;
    }
    const { curCommitInfo } = this.props;
    this.props.postInfo(
      {
        note: value,
        parent_id: '',
        sha: curCommitInfo.id,
      },
      () => {
        this.setState({
          value: '',
        });
      },
    );
  };

  onKeyDown = (e) => {
    if (e[ctrlKey] && e.keyCode === KEYCODE.ENTER) {
      this.onSubmitWhole(this.state.value);
    }
  };

  render() {
    const { commentList } = this.props;
    const { isShowMore } = this.state;
    const conversationsLength = this.getConversationsLength(commentList);
    const moreCommitsLength = conversationsLength - 8;

    return (
      <div
        className="commit-right-content-comment"
        id="commit_comment_id"
        ref={this.props.commitRef}
      >
        <div className="commit-right-content-comment-header">评论</div>
        <div className="commit-right-content-comment-top-switch">
          {conversationsLength > 8 ? (
            <div className="show-more-btn">
              <Button
                type="primary"
                text
                onClick={() => {
                  this.setState({
                    isShowMore: !isShowMore,
                  });
                }}
              >
                <span style={{ marginRight: '14px' }}>
                  <YunxiaoIcon type="more-line" />
                </span>
                <span>
                  {isShowMore
                    ? intl.get(
                        {
                          id: 'code-assets.commitDetail.detail.DisplayEarlierMorecommitslengthComments',
                          defaultMessage: '显示较早的{moreCommitsLength}条评论',
                        },
                        { moreCommitsLength },
                      )
                    : intl.get({
                        id: 'code-assets.commitDetail.detail.HideEarlierComments',
                        defaultMessage: '隐藏较早的评论',
                      })}
                </span>
              </Button>
            </div>
          ) : null}
        </div>
        {this.renderCommentList()}
        <div className="commit-right-content-comment-list">
          <div className="commit-right-content-comment-list-avatar">
            {window.FORCE?.user?.avatar ? (
              <ImageAvatar img={window.FORCE?.user?.avatar} />
            ) : (
              <TextAvatar text={window.FORCE?.user?.nickname.slice(0, 1)} />
            )}
          </div>
          <div className="commit-right-content-comment-list-textarea">
            <Input.TextArea
              placeholder={`输入评论，支持 ${ctrlTxt} + Enter 提交评论`}
              aria-label="TextArea"
              className="content-comment-list-textarea"
              onKeyDown={this.onKeyDown}
              value={this.state.value}
              onChange={(v) => this.setState({ value: v })}
            />
            <div className="commit-right-content-comment-submit-button">
              <Button type="primary" onClick={() => this.onSubmitWhole(this.state.value)}>
                提交评论
              </Button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default commitComment;
